package com.ywm.vod.conroller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.ywm.commonUtil.R;
import com.ywm.vod.service.VodService;
import com.ywm.vod.utils.ConstanVodUtils;
import com.ywm.vod.utils.InitObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/eduvod/vod")
//@CrossOrigin
public class VodController {
    @Autowired
    private VodService vodService;

    @ApiOperation("上传视频")
    @PostMapping("/uploadAlyVideo")
    public R uploadAlyVideo(MultipartFile file) throws Exception {
        //返回上传视频的ID
        String VideoId=vodService.uploadAlyVideo(file);
        System.out.println("=========");
        return R.ok().data("vidoId",VideoId);
    }
    // TODO
    //根据视频ID删除视频
    @DeleteMapping("/removeAlyVideo/{id}")
    public R removeAlyVideo(@PathVariable String id){
        try {
            //初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstanVodUtils.ACCESS_KEY_ID, ConstanVodUtils.ACCESS_KEY_SECRET);
            //创建视频删除对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //设置需要删除的视频ID
            request.setVideoIds(id);
            //调用初始化方法实现删除
            DeleteVideoResponse response = client.getAcsResponse(request);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
//        vodService.removeAlyVideo(id);
        return R.ok();
    }

    //根据视频Id获取视频凭证
    //根据id获取视频播放凭证
    @GetMapping("/getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) throws Exception {
        try{
            //根据视频id获得视频播放地址
            //创建初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstanVodUtils.ACCESS_KEY_ID, ConstanVodUtils.ACCESS_KEY_SECRET);
            //创建获取视频地址request和response
            GetVideoPlayAuthRequest request= new GetVideoPlayAuthRequest();
            GetVideoPlayAuthResponse response;
            //向request对象设置视频ID
            request.setVideoId(id);
            //调用初始化对象里面的方法，得到视频的凭证
            response=client.getAcsResponse(request);
            return R.ok().data("playAuth",response.getPlayAuth());
        }catch (Exception e){
            throw new Exception("获取凭证失败");
        }
    }

    @GetMapping("test")
    public R test(){
        return R.ok().data("String","===success===");
    }
}
